package com.pie4cloud.pie.job.executor.job;

import com.alibaba.fastjson.JSON;
import com.pie4cloud.pie.common.core.constant.SecurityConstants;
import com.pie4cloud.pie.common.core.util.R;
import com.pie4cloud.pie.job.api.consumer.IHanlderConsumer;
import com.pie4cloud.pie.job.api.consumer.annotation.Hanlder;
import com.pie4cloud.pie.job.api.dto.CallBackDto;
import com.pie4cloud.pie.job.api.entity.DispenseCongfigEntity;
import com.pie4cloud.pie.job.api.entity.DispenseTimingEntity;
import com.pie4cloud.pie.job.api.entity.PlaybillEntity;
import com.pie4cloud.pie.job.api.feign.RemoteDispenseCongfigService;
import com.pie4cloud.pie.job.api.vo.TimeLevelVo;
import com.pie4cloud.pie.job.executor.service.DispenseToolService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@Service
@RequiredArgsConstructor
@Hanlder(handler = "dispenseHandler")
public class DispenseTimingHandlerService implements IHanlderConsumer {
	@Autowired
    private DispenseToolService dispenseToolService;
	private final RemoteDispenseCongfigService remoteDispenseCongfigService;

	@Override
	public R execute(String jobInfoEntity, CallBackDto callBackDto) throws Exception {
		R<String> result= new R<>();
		DispenseTimingEntity dispenseTimingEntity=JSON.parseObject(jobInfoEntity,DispenseTimingEntity.class);
		DispenseCongfigEntity dispenseCongfigEntity=dispenseTimingEntity.getDispenseCongfig();
		TimeLevelVo timeLevelVo=new TimeLevelVo();
		SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			dispenseCongfigEntity.getDispenseTiming().setTriggerLastTime(format.parse("2021-05-07 01:00:00").getTime());
			//timeLevelVo.setEndTime(format.parse("2021-05-08 00:00:00").getTime());
			//timeLevelVo.setTimeKey(format.parse("2021-05-07 00:00:00").getTime());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		R<PlaybillEntity> playbillEntityR=remoteDispenseCongfigService.findByDdataId(dispenseCongfigEntity.getDdataId(), SecurityConstants.FROM_IN);
		PlaybillEntity playbillEntity=playbillEntityR.getData();
		Date lastTime=dispenseToolService.getLastTriggerTime(playbillEntity.getJobCron(),new Date(dispenseCongfigEntity.getDispenseTiming().getTriggerLastTime()));
		Date nextTime=dispenseToolService.getNextTriggerTime(playbillEntity.getJobCron(),lastTime);
		timeLevelVo.setStartTime(lastTime.getTime());
		timeLevelVo.setEndTime(nextTime.getTime());
		timeLevelVo.setTimeKey(lastTime.getTime());
		if(dispenseCongfigEntity.getDispenseTiming().getCollectType()==0){
			dispenseToolService.scanDataBase(dispenseCongfigEntity,timeLevelVo,result);
		}else {
			dispenseToolService.scanPreFolder(dispenseCongfigEntity,timeLevelVo,result);
		}
		return result;
	}


}
